﻿using System;
using System.Windows.Forms;
using SdmxMl.Common;
using SdmxMl.Structure;
using SdmxMl.Helper;
using SdmxMl.Manager;
using SdmxMl.Panels;

namespace SdmxMl.UC
{
    /// <summary> Base SDMX artefact visual control  </summary>
    public class UcBaseAttrib : UserControl
    {
        #region Internal Members

        protected bool _isFinal;
        protected UcMlText ucmlText;
        protected Artefact ar;
        protected TreeNode theNode;
        protected bool inBinding;
        protected PanelAnnotationList pannelAnnot;

        #endregion

        #region C'tor

        public UcBaseAttrib()
        {
            Visible = false;
            ucmlText = new UcMlText();
        }
        #endregion

        #region Bind item

        /// <summary>Bind item in current node tag </summary>
        /// <param name="node">Main tree view active node</param>
        /// <param name="pannel">Annotation panel</param>
        /// <param name="isFinal">Is attribute finalized</param>
        public bool BindFromNode(TreeNode node, PanelAnnotationList pannel, bool isFinal)
        {
            ar = null;
            pannelAnnot = pannel;
            _isFinal = isFinal;
            theNode = node;

            if (node != null)
            {
                ar = node.Tag as Artefact;
                BindToControls();
            }
            return Visible;
        }

        /// <summary> Reflects item content in controls of the view </summary>
        protected virtual void BindToControls()
        {
        }

        #endregion

        #region Update item & Node content from detail View

        public bool UpdateNodeTag(TreeNode node)
        {
            if (theNode != null)
            {
                BindFromControls();
                if (ar != null && theNode.Text != ar.ToString())
                    theNode.Text = ar.ToString();
            }

            return false; // true on error
        }


        protected virtual void BindFromControls()
        {

        }
        #endregion

        #region IsFinal validation control

        protected void checkBoxIsFinal_CheckedChanged(object sender, System.EventArgs e)
        {
            if (inBinding)
                return;
            CheckBox ckb = sender as CheckBox;
            if (ckb != null)
            {
                UpdateNodeTag(theNode);

                // If checked process a XSD validation of artefact
                if (ar.IsFinal)
                {
                    bool removeFinal = ValidateWithXsd() == false;

                    // Special DSD, check for TimeSerie
                    KeyFamilyType dsd = this.ar as KeyFamilyType;
                    if (!removeFinal && dsd != null && dsd.TimeDimension == null)
                    {
                        if (MessageBox.Show("« Any key family which will be used for time-series formats (GenericData, CompactData, and UtilityData) must include the time dimension. » \n" +
                            "Proceed finalization ? ", "Caution", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.Cancel)
                        {
                            removeFinal = true;
                        }
                    }
                    if (removeFinal)
                    {
                        inBinding = true;
                        ckb.Checked = false;
                        UpdateNodeTag(theNode);
                        inBinding = false;
                    }
                }

                pannelAnnot.BindFromNode(theNode.Tag, ckb.Checked);
                BindFromNode(theNode, pannelAnnot, ckb.Checked);
            }
        }

        protected bool ValidateWithXsd()
        {
            string strFilename = string.Empty;
            bool isValid = true;
            try
            {
                ArtefactManager am = theNode.Parent.Tag as ArtefactManager;

                strFilename = am.SaveTempArtefact(ar);

                XmlValidator xv = new XmlValidator();
                string err = xv.ValidateSdmxStructure(strFilename, System.EventArgs.Empty);
                if (err.Length > 0)
                {
                    MessageBox.Show("Caution: Artefact validation with XML schema detected some errors!" +
                    System.Environment.NewLine + System.Environment.NewLine + err, "XSD Validation Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    isValid = false;
                }
            }

            catch (Exception ex)
            {
                string s = ex.Message;
                isValid = false;
            }
            finally
            {
                if (strFilename.Length > 0)
                {
                    try { System.IO.File.Delete(strFilename); }
                    catch { }
                }
            }
            return isValid;
        }
        #endregion
    }
}
